package com.interest.business.utils;

import com.interest.business.base.RequestHeaderBean;
import com.interest.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * 参数校验工具
 */
@Component
public class OutParameterValidator {
    private static final Logger LOG = LoggerFactory.getLogger(OutParameterValidator.class);

    @Value("${interest.sha256key}")
    private String key;
    /**
     *校验参数
     * @param data
     * @return
     */
    public boolean validate(Object data, RequestHeaderBean requestHeader) throws Exception {
        Map<String,Object> properteis = getProperties(data);
        String str = properteis.entrySet().stream().map(item->item.getKey()+"="+item.getValue()).collect(Collectors.joining("&"));
        str+=requestHeader.getNonceStr()+requestHeader.getTimestamp();
        String base64Str = Base64Utils.encodeToString(str.getBytes("utf-8"));
        return StringUtils.equals(HmacSHA256Util.hmacSHA256(key,base64Str),requestHeader.getSignature());
    }
    /**
     * 获取所有属性及值 并通过有序方式返回
     *
     * @param object
     * @return
     */
    private static Map<String, Object> getProperties(Object object) {
        Map<String, Object> properties = new TreeMap<>();
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                String fieldName = field.getName();
                Object fieldValue = field.get(object);
                properties.put(fieldName, fieldValue);
            } catch (IllegalAccessException e) {
                LOG.error("获取对象属性值失败:",e);
            }
        }
        return properties;
    }
}
